package es.xpt.ysf.commons.jaas.view;

import java.util.List;
import java.util.TreeSet;

import javax.faces.component.UIData;

import es.xpt.ysf.view.model.LocaleDescriptionBean;
import es.xpt.ysf.jaas.model.PrivelegesGroupBean;
import es.xpt.ysf.model.Item;
import es.xpt.ysf.view.Helper;

public class RolesHelper extends Helper {
	private UIData row;

	public String createTree(PrivelegesGroupBean group,
			TreeSet<String> selected, String locale) {
		contador = 0;
		String s = crearSubArbol(group, selected, locale, -1).getDescription();
		return "var Tree = new Array(" + contador + ")\n" + s;
	}

	private int contador = 0;

	private Item crearSubArbol(PrivelegesGroupBean bloque,
			TreeSet<String> selected, String locale, int padre) {
		if (bloque != null) {
			List<PrivelegesGroupBean> opciones = bloque.getGroups();
			if (opciones != null && opciones.size() > 0) {
				int verdaderos = 0, falsos = 0;
				StringBuffer aDevolver = new StringBuffer();
				for (int i = 0; i < opciones.size(); i++) {
					PrivelegesGroupBean b = opciones.get(i);
					LocaleDescriptionBean description = b
							.getDescription(locale);

					aDevolver.append(" Tree[" + contador + "] = new Array ('"
							+ b.getId() + "'," + padre + ",'"
							+ (description!=null?description.getName():b.getId()) + "','"
							+ (description!=null?description.getDescription():"") + "',");
					contador++;

					if (b.getGroups() != null && b.getGroups().size() > 0) {
						Item cdh = crearSubArbol(b, selected, locale,
								contador - 1);
						if ("5".equals(cdh.getCode()))
							verdaderos++;
						else if ("6".equals(cdh.getCode()))
							falsos++;
						else {
							verdaderos++;
							falsos++;
						}
						aDevolver.append(cdh.getCode() + ");\n"
								+ cdh.getDescription());
					} else {
						boolean state = selected.contains(b.getId());
						if (state)
							verdaderos++;
						else
							falsos++;
						aDevolver.append((state ? "5" : "6") + ");\n");
					}
				}
				String contains = "4";
				if (falsos == 0)
					contains = "5";
				if (verdaderos == 0)
					contains = "6";
				return new Item(contains, aDevolver.toString());
			}
		}
		return new Item();
	}

	/**
	 * @return the row
	 */
	public UIData getRow() {
		return row;
	}

	/**
	 * @param row
	 *            the row to set
	 */
	public void setRow(UIData row) {
		this.row = row;
	}

}
